package com.renshuai.demo.mybatis.config;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.renshuai.demo.mybatis.entity.Order;

/**
 * Hello world!
 *
 */
@org.springframework.context.annotation.Configuration
//@MapperScan("com.renshuai.demo.mybatis")
@ComponentScan("com.renshuai.demo.mybatis")
//@Import(MyImportBeanDefinitionRegistrar.class)
public class AppConfig {
	
	public static void main(String[] args) {
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
    	Environment environment = new Environment("development", transactionFactory, dataSource());
    	Configuration configuration = new Configuration(environment);
    	configuration.addMapper(OrderMapper.class);
    	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    	SqlSession sqlSession = sqlSessionFactory.openSession();
    	
    	Order order = sqlSession.selectOne("com.renshuai.demo.mybatis.config.OrderMapper.selectBlog", 1);
    	OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    	Order order2 = mapper.selectOrder(2);
    	System.out.println(order.toString());
    	System.out.println(order2.toString());
	}
    
    @Bean
    public static DataSource dataSource() {
    	
    	DriverManagerDataSource dataSource = new DriverManagerDataSource();
    	dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    	dataSource.setUrl("jdbc:mysql://192.168.15.16:3306/db_seata?"
    			+ "serverTimezone=Hongkong&useSSL=false&useUnicode=true&characterEncoding=UTF-8");
    	dataSource.setUsername("root");
    	dataSource.setPassword("root");
    	return dataSource;
    }
    
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
    	
    	SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    	sqlSessionFactoryBean.setDataSource(dataSource());
    	return sqlSessionFactoryBean.getObject();
	}
}
